package com.security.demo.service.security;

import com.security.demo.entity.Role;
import com.security.demo.entity.User;
import com.security.demo.service.RoleService;
import com.security.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author H
 * @date 2023/1/12
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取数据库用户信息
        User dbUser = userService.getUserByName(username);
        // 获取数据库角色信息
        List<Role> dbRoles = roleService.getRolesByUserName(username);

        // 转换为UserDetails对象
        UserDetails userDetails = getUserDetails(dbUser, dbRoles);
        return userDetails;
    }

    private UserDetails getUserDetails(User dbUser, List<Role> dbRoles) {
        // 权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 赋予查询到的角色
        for (Role dbRole : dbRoles) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(dbRole.getRoleName());
            authorities.add(authority);
        }
        // 创建UserDetails对象，设置用户名，密码和权限
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(dbUser.getUserName(), dbUser.getPwd(), authorities);
        return userDetails;
    }

}
